//
//  DetailOfRouteViewController.m
//  Follow Me
//
//  Created by apple on 2017/5/13.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "DetailOfRouteViewController.h"


@interface DetailOfRouteViewController ()<MKMapViewDelegate,CLLocationManagerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) moreActionView *moreAct;
@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,strong) NSMutableArray *locationMutableArray;
@property (nonatomic,strong) NSMutableArray *NewLocationMutableArray;
@end

@implementation DetailOfRouteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *routeInfo = [Routes findByAttribute:@"routeName" withValue:[MainModel model].routeMsg.routeName];
    Routes *savedRoute = [routeInfo firstObject];
    self.detailOfRouteNameLabel.text = savedRoute.routeName;
    self.detailOfRouteTimeLabel.text = savedRoute.time;
    self.detailOfRouteDistanceLabel.text = savedRoute.distance;
    self.detailOfRouteDescriptionLabel.text = savedRoute.routeDescription;;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    self.detailOfRouteDateLabel.text = [dateFormatter stringFromDate:savedRoute.routeDate];
    
    self.detailOfRouteMapView.delegate = self;
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.detailOfRouteMapView setMapType:MKMapTypeHybridFlyover];
    
    //nsdata转数组
    self.locationMutableArray = [NSKeyedUnarchiver unarchiveObjectWithData:savedRoute.mapData];
    [self.locationManager startUpdatingLocation];
    // Do any additional setup after loading the view.
}
//循迹按钮
- (IBAction)detailOfRouteFollowButton:(id)sender {
    
    self.detailOfRouteMapView.showsUserLocation = true;
    colourChoice = 1;
    self.NewLocationMutableArray = [[NSMutableArray alloc]init];
    self.detailOfRouteMapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}
//更新循迹轨迹
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    if (self.NewLocationMutableArray.count > 1) {
        
        //从位置数组中取出最新的位置数据
        NSString *locationStr = self.NewLocationMutableArray.lastObject;
        NSArray *temp = [locationStr componentsSeparatedByString:@","];
        NSString *latitudeStr = temp[0];
        NSString *longitudeStr = temp[1];
        CLLocationCoordinate2D NstartCoordinate = CLLocationCoordinate2DMake([latitudeStr doubleValue], [longitudeStr doubleValue]);
        
        //当前确定到的位置数据
        CLLocationCoordinate2D NendCoordinate;
        NendCoordinate.latitude = userLocation.coordinate.latitude;
        NendCoordinate.longitude = userLocation.coordinate.longitude;
        
        //移动距离的计算
        double meters = [self calculateDistanceWithStart:NstartCoordinate end:NendCoordinate];
        
        //为了美化移动的轨迹,移动的位置超过10米,方可添加进位置的数组
        if (meters >= 15){
            
            NSLog(@"添加进位置数组");
            NSString *locationString = [NSString stringWithFormat:@"%f,%f",userLocation.coordinate.latitude, userLocation.coordinate.longitude];
            [self.locationMutableArray addObject:locationString];
            
            //开始绘制轨迹
            CLLocationCoordinate2D pointsToUse[2];
            pointsToUse[0] = NstartCoordinate;
            pointsToUse[1] = NendCoordinate;
            //调用 addOverlay 方法后,会进入 rendererForOverlay 方法,完成轨迹的绘制
            MKPolyline *lineOne = [MKPolyline polylineWithCoordinates:pointsToUse count:2];
            [self.detailOfRouteMapView addOverlay:lineOne];
        }else{
            
        }
    }else{
        //存放位置的数组,如果数组包含的对象个数为0,那么说明是第1次进入,将当前的位置添加到位置数组
        if(userLocation.coordinate.latitude!=0.00000&&userLocation.coordinate.longitude!=0.00000){
            NSString *locationString = [NSString stringWithFormat:@"%f,%f",userLocation.coordinate.latitude, userLocation.coordinate.longitude];
            [self.NewLocationMutableArray addObject:locationString];
        }
    }
}
#pragma mark - 距离测算
- (double)calculateDistanceWithStart:(CLLocationCoordinate2D)start end:(CLLocationCoordinate2D)end {
    
    double meter = 0;
    
    double startLongitude = start.longitude;
    double startLatitude = start.latitude;
    double endLongitude = end.longitude;
    double endLatitude = end.latitude;
    
    double radLatitude1 = startLatitude * M_PI / 180.0;
    double radLatitude2 = endLatitude * M_PI / 180.0;
    double a = fabs(radLatitude1 - radLatitude2);
    double b = fabs(startLongitude * M_PI / 180.0 - endLongitude * M_PI / 180.0);
    
    double s = 22 * asin(sqrt(pow(sin(a/2),2) + cos(radLatitude1) * cos(radLatitude2) * pow(sin(b/2),2)));
    s = s * 6378137;
    
    meter = round(s * 10000) / 10000;
    //kiloMeter =meter/1000;
    return meter;
}

//updating location
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    MKCoordinateSpan span;
    span.latitudeDelta = 0.003f;
    span.longitudeDelta = 0.003f;
    
    
    int i;
    for (i = 0;i+1<self.locationMutableArray.count;i++)
    {
        
        NSString *locationStr = self.locationMutableArray[i];
        NSArray *temp = [locationStr componentsSeparatedByString:@","];
        NSString *latitudeStr = temp[0];
        NSString *longitudeStr = temp[1];
        CLLocationCoordinate2D startCoordinate =CLLocationCoordinate2DMake([latitudeStr doubleValue], [longitudeStr doubleValue]);
        NSString *locationStr1 = self.locationMutableArray[i+1];
        NSArray *temp1 = [locationStr1 componentsSeparatedByString:@","];
        NSString *latitudeStr1 = temp1[0];
        NSString *longitudeStr1 = temp1[1];
        CLLocationCoordinate2D endCoordinate = CLLocationCoordinate2DMake([latitudeStr1 doubleValue], [longitudeStr1 doubleValue]);
        //开始绘制轨迹
        colourChoice = 0;
        CLLocationCoordinate2D pointsToUse[2];
        pointsToUse[0] = startCoordinate;
        pointsToUse[1] = endCoordinate;
        //调用 addOverlay 方法后,会进入 rendererForOverlay 方法,完成轨迹的绘制
        MKPolyline *lineOne = [MKPolyline polylineWithCoordinates:pointsToUse count:2];
        [self.detailOfRouteMapView addOverlay:lineOne];
        
    }
    NSInteger m = (self.locationMutableArray.count)/2;
    NSString *locationStr2 = self.locationMutableArray[m];
    NSArray *temp2 = [locationStr2 componentsSeparatedByString:@","];
    NSString *latitudeStr2 = temp2[0];
    NSString *longitudeStr2 = temp2[1];
    CLLocationCoordinate2D centerCoordinate =CLLocationCoordinate2DMake([latitudeStr2 doubleValue], [longitudeStr2 doubleValue]);
    MKCoordinateRegion region=MKCoordinateRegionMake(centerCoordinate, span);
    [self.detailOfRouteMapView setRegion:region animated:true];
    
    
    [manager stopUpdatingLocation];
}
//画线
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    
    if ([overlay isKindOfClass:[MKPolyline class]]){
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        MKPolylineView *polyLineView = [[MKPolylineView alloc] initWithPolyline:overlay];
        polyLineView.lineWidth = 10; //折线宽度
        if (colourChoice == 0){
            polyLineView.strokeColor = [UIColor yellowColor]; //折线颜色
        }else{
            polyLineView.strokeColor = [UIColor redColor]; //折线颜色
        }
        return (MKOverlayRenderer *)polyLineView;
#pragma clang diagnostic pop
    }
    return nil;
}

- (IBAction)moreActionView:(id)sender {
    if (!self.moreAct){
        self.moreAct = [[NSBundle mainBundle]loadNibNamed:@"moreActionView" owner:self options:nil].firstObject;
    }
    
    [self.view addSubview:self.moreAct];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
